package com.shanjupay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author whb
 * @create 2021-11-19 13:46
 * @desciption 短信服务Service实现类
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private ConfigurableApplicationContext applicationContext;


    /**
     * 获取短信验证key
     *
     * @param phone 手机号码
     * @return
     */
    @Override
    public String getSmsKey(String phone) {
        String url = applicationContext.getEnvironment().getProperty("sms.url");//验证码服务发送请求的地址
        String effectiveTime = applicationContext.getEnvironment().getProperty("sms.effectiveTime");//验证信息有效期(秒)
        String sms_url = url + "/generate?name=sms&effectiveTime=" + effectiveTime;//想短信验证码服务发送请求地址

        //请求体
        Map<String, Object> body = new HashMap<>();
        body.put("mobile", phone);
        //请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        //请求消息，传入请求体body和请求头httpHeaders
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(body, httpHeaders);

        //向url请求
        ResponseEntity<Map> exchange = null;
        Map<String, Object> responseMap = null;
        try {
            exchange = restTemplate.exchange(sms_url, HttpMethod.POST, httpEntity, Map.class);
            log.info("请求短信验证码服务，得到响应：{}", JSON.toJSONString(exchange));
            responseMap = exchange.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            throw new RuntimeException("请求短信验证码失败！");
        }

        if (responseMap == null || responseMap.get("result") == null) {
            throw new RuntimeException("请求短信验证码失败！");
        }

        Map<String, Object> resultMap = (Map<String, Object>) responseMap.get("result");
        //请求短信验证服务，获得响应体中的key
        String key = (String) resultMap.get("key");
        log.info("得到发送短信验证码对应的key：{}", key);
        return key;
    }

    /**
     * 校验短信验证码
     *
     * @param verifiyKey  验证码的key
     * @param verifiyCode 验证码
     */
    @Override
    public void checkVerifiyCode(String verifiyKey, String verifiyCode) throws BusinessException {
        String url = applicationContext.getEnvironment().getProperty("sms.url");//验证码服务发送请求的地址
        //校验短信验证码的url
        String verifiy_url = url + "/verify?name=sms&verificationCode=" + verifiyCode + "&verificationKey=" + verifiyKey;

        Map<String, Object> verifiyMap = null;
        try {
            //使用restTemplate请求验证码服务，校验短信验证码
            ResponseEntity<Map> exchange = restTemplate.exchange(verifiy_url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
            log.info("请求验证吗服务，校验短信验证码，得到响应：{}", JSON.toJSONString(exchange));
            verifiyMap = exchange.getBody();
        } catch (RestClientException e) {
            e.printStackTrace();
            //throw new RuntimeException("校验验证码失败！");
            throw new BusinessException(CommonErrorCode.E_100102);//使用自定义业务异常类
        }

        if (verifiyMap == null || verifiyMap.get("result") == null || !(Boolean) verifiyMap.get("result")) {
            //throw new RuntimeException("校验验证码失败！");
            throw new BusinessException(CommonErrorCode.E_100102);//使用自定义业务异常类
        }
    }
}
